package com.aizhixin.lab.task.service;

import com.aizhixin.lab.account.dto.AccountDTO;
import com.aizhixin.lab.task.domain.*;
import com.aizhixin.lab.task.entity.TaskQuestion;
import com.aizhixin.lab.task.entity.TaskQuestionChoice;
import com.aizhixin.lab.task.entity.TaskStuInfor;
import com.aizhixin.lab.task.repository.TaskStuInforRepository;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.common.core.DataValidity;
import com.aizhixin.lab.common.dto.SortDTO;
import com.aizhixin.lab.common.utils.PageJdbcUtil;
import com.aizhixin.lab.task.entity.Task;
import com.aizhixin.lab.task.repository.TaskRepository;

@Slf4j
@Service
@Transactional
public class TaskService {
    @Autowired
    private TaskRepository taskRepository;
    @Autowired
    private PageJdbcUtil pageJdbcUtil;
	@Autowired
	private TaskStuInforRepository taskStuInforRepository;
    @Autowired
    private TaskQuestionChoiceService taskQuestionChoiceService;
    @Autowired
    private TaskQuestionsService taskQuestionsService;
    public Map<String, Object> save(TaskDomain dto, Long userId) {
        Map<String, Object> result = new HashMap<>();
        if (StringUtils.isEmpty(dto.getId())) {
            Task task = new Task();
            BeanUtils.copyProperties(dto, task);
            task.setCreatedBy(userId);
            task.setCreatedDate(new Date());
            task.setId(UUID.randomUUID().toString());
            task.setCourseChapterId(dto.getCourseChapterId());
            task.setCourseMinutiaId(dto.getCourseMinutiaId());
            task.setQuestionsNum(0);
            task.setIsCountDown(dto.getIsCountDown());
            task.setCountDown(dto.getCountDown());
            task = taskRepository.save(task);
            result.put(ApiReturnConstants.DATA, task);
            result.put(ApiReturnConstants.SUCCESS, true);
        } else {
            Task task = taskRepository.findOne(dto.getId());
            if (task != null) {
                task.setTaskName(dto.getTaskName());
                task.setLastModifiedDate(new Date());
                task.setLastModifiedBy(userId);
                task.setIsCountDown(dto.getIsCountDown());
                task.setCountDown(dto.getCountDown());
                task = taskRepository.save(task);
                result.put(ApiReturnConstants.DATA, task);
                result.put(ApiReturnConstants.SUCCESS, true);
            } else {
                result.put(ApiReturnConstants.SUCCESS, false);
                result.put(ApiReturnConstants.ERROR, "任务信息不存在！");
            }
        }
        return result;
    }
    //将上传的excel文件转换为List集合
    public  List<TaskQuestionDomain> fileTransformList(File file) throws IOException, BiffException {
        Workbook workbook = Workbook.getWorkbook(file);
        Sheet sheet = workbook.getSheet(0);
        List<TaskQuestionDomain> list=new ArrayList<>();
        int rows = sheet.getRows();
        for (int r=1;r<rows;r++){
            TaskQuestionDomain taskQuestionDomain = new TaskQuestionDomain();
            taskQuestionDomain.setQuestionType(Integer.parseInt(sheet.getCell(0, r).getContents()));
            taskQuestionDomain.setOrderNum(Integer.parseInt(sheet.getCell(1,r).getContents()));
            taskQuestionDomain.setQuestionContent(sheet.getCell(2,r).getContents());
            taskQuestionDomain.setAnalysis(sheet.getCell(3,r).getContents());
            taskQuestionDomain.setAnswer(sheet.getCell(4,r).getContents());
            if (taskQuestionDomain.getQuestionType()==10||taskQuestionDomain.getQuestionType()==20){
                List<TaskQuestionChoiceDomain> choicelist = new ArrayList<TaskQuestionChoiceDomain>();
                for (int j=6;j<Integer.parseInt(sheet.getCell(5,r).getContents())+6;j++){
                    TaskQuestionChoiceDomain taskQuestionChoiceDomain = new TaskQuestionChoiceDomain();
                    taskQuestionChoiceDomain.setOption(((char)('A'+j-6))+"");
                    taskQuestionChoiceDomain.setChoiceContent(sheet.getCell(j,r).getContents());
                    choicelist.add(taskQuestionChoiceDomain);
                }
                taskQuestionDomain.setChoicelist(choicelist);
            }
            list.add(taskQuestionDomain);


        }
        return list;
    }

    public void save(Task task) {
        taskRepository.save(task);
    }
   //导入任务
    public Task save(ImportTaskDomain domain,AccountDTO dto,Integer questionNum){
        Task task = new Task();
        task.setId(UUID.randomUUID().toString());
        task.setQuestionsNum(questionNum);
        task.setTaskName(domain.getTaskName());
        task.setCourseId(domain.getCourseId());
        task.setTemplateId(domain.getTemplateId());
        task.setCreatedBy(dto.getId());
        if (domain.getCourseChapterId()!=null&&!"".equals(domain.getCourseChapterId())){
            task.setCourseChapterId(domain.getCourseChapterId());
        }
        if (domain.getCourseMinutiaId()!=null&&!"".equals(domain.getCourseMinutiaId())){
            task.setCourseMinutiaId(domain.getCourseMinutiaId());
        }
        taskRepository.save(task);
        return task;
    }
    public List saveQuestionAndAnswer(List<TaskQuestionDomain> domains,Task task,AccountDTO dto){
        List<TaskQuestion> taskQuestionList=new ArrayList<>();
        for (TaskQuestionDomain t: domains){
            TaskQuestion taskQuestion = new TaskQuestion();
            taskQuestion.setId(UUID.randomUUID().toString().replaceAll("-",""));
            taskQuestion.setQuestionContent(t.getQuestionContent());
            taskQuestion.setQuestionType(t.getQuestionType());
            taskQuestion.setTaskId(task.getId());
            taskQuestion.setOrderNum(t.getOrderNum());
            taskQuestion.setAnalysis(t.getAnalysis());
            taskQuestion.setAnswer(t.getAnswer());
            taskQuestion.setCreatedBy(dto.getId());
            if (taskQuestion.getQuestionType()==10||taskQuestion.getQuestionType()==20){
                List<TaskQuestionChoice> choiceList=new ArrayList<>();
                for (TaskQuestionChoiceDomain tq:t.getChoicelist()){
                    TaskQuestionChoice taskQuestionChoice = new TaskQuestionChoice();
                    taskQuestionChoice.setChoiceContent(tq.getChoiceContent());
                    taskQuestionChoice.setOption(tq.getOption());
                    taskQuestionChoice.setTaskQuestionId(taskQuestion.getId());
                    taskQuestionChoice.setId(UUID.randomUUID().toString().replaceAll("-",""));
                    choiceList.add(taskQuestionChoice);
                }
                taskQuestionChoiceService.saveChoiceList(choiceList);
            }
            taskQuestionList.add(taskQuestion);
        }
        taskQuestionsService.save(taskQuestionList);

        return taskQuestionList;
    }

    public Task findById(String id) {
        return taskRepository.findByIdAndDeleteFlag(id, DataValidity.VALID.getState());
    }

    RowMapper<TaskDomain> taskRm = new RowMapper<TaskDomain>() {

        @Override
        public TaskDomain mapRow(ResultSet rs, int rowNum)
                throws SQLException {
            // TODO Auto-generated method stub
            TaskDomain domain = new TaskDomain();
            domain.setId(rs.getString("task_id"));
            domain.setCourseName(rs.getString("course_name"));
            domain.setTaskName(rs.getString("TASK_NAME"));
            domain.setCreatedDate(rs.getTimestamp("CREATED_DATE"));
            domain.setCreatorName(rs.getString("user_name"));
            domain.setQuestionsNum(rs.getInt("QUESTIONS_NUM"));
            return domain;
        }
    };

    public <T> Map<String, Object> findTaskPage(QueryTaskDomain domain) {

        String querySql = "select c.`name` as course_name,t.id as task_id,t.TASK_NAME,t.CREATED_DATE,t.QUESTIONS_NUM,u.`name` as user_name from `t_task` as t LEFT JOIN `t_user` u ON t.CREATED_BY = u.id LEFT JOIN `c_course` as c ON t.COURSE_ID = c.id where c.template_id =" + domain.getTemplateId() + " and t.DELETE_FLAG =0 AND u.delete_flag =0 and c.delete_flag =0  ";
        String countSql = "select count(*) from `t_task` as t LEFT JOIN `t_user` u ON t.CREATED_BY = u.id LEFT JOIN `c_course` as c ON t.COURSE_ID = c.id where c.template_id =" + domain.getTemplateId() + "  and t.DELETE_FLAG =0 AND u.delete_flag =0 and c.delete_flag =0 ";

//			if (null != domain.getChapterId() && domain.getChapterId().intValue() > 0L) {
//				querySql += " and lr.CHAPER_ID=" + domain.getChapterId() + "";
//				countSql += " and lr.CHAPER_ID=" + domain.getChapterId() + "";
//			}  
//			if (!StringUtils.isEmpty(domain.getCourseClassId())) {
//				querySql += " and lr.COURSE_CLASS_ID='" + domain.getCourseClassId() + "'";
//				countSql += " and lr.COURSE_CLASS_ID='" + domain.getCourseClassId() + "'";
//			} 
//			if (!StringUtils.isEmpty(domain.getName())) {
//				querySql += " and u.NAME like '%" + domain.getName() + "%'";
//				countSql += " and u.NAME like '%" + domain.getName() + "%'";
//			}

        List<SortDTO> sort = new ArrayList<SortDTO>();
        SortDTO dto = new SortDTO();
        dto = new SortDTO();
        dto.setKey("t.CREATED_DATE");
        dto.setAsc(false);
        sort.add(dto);

        return pageJdbcUtil.getPageInfor(domain.getPageSize(),
                domain.getPageNumber(), taskRm, sort, querySql, countSql);
    }

//    public <T> Map<String, Object> getTaskList(QueryDomain domain, AccountDTO dto) {
////        String sql = "SELECT cc.name as course_name,ls.commit1,ls.TASK_NAME,ls.total,ls.yi FROM c_course as cc RIGHT JOIN(SELECT t.COURSE_ID as COURSE_ID1,t.CREATED_DATE, t.TASK_NAME,COUNT(ts.commit_time) AS commit1,COUNT(ts.release_task_id)AS total,COUNT(ts.batch_time) AS yi FROM t_task AS t LEFT JOIN t_task_stu_infor AS ts ON t.id = ts.release_task_id) as ls ON ls.COURSE_ID1 = cc.id  ";
//        String querySql="SELECT tt.id,tt.TASK_NAME,cc.`name` FROM t_task as tt LEFT JOIN c_course as cc on tt.COURSE_ID=cc.id";
//        String countSql="SELECT COUNT(*) FROM t_task as ta WHERE ta.CREATED_BY="+dto.getAccountId();
//        if (domain.getCourseId()!=null&&!"".equals(domain.getCourseId())){
//			querySql +="where cc.id ="+domain.getCourseId();
//			countSql+=" and ta.COURSE_ID ="+domain.getCourseId();
//		}
//		List<SortDTO> sort = new ArrayList<SortDTO>();
//		SortDTO sortDto = new SortDTO();
//		sortDto.setKey("tt.CREATED_DATE");
//		sortDto.setAsc(true);
//		sort.add(sortDto);
//        RowMapper<TaskListDomain> taskRm = new RowMapper<TaskListDomain>() {
//
//            @Override
//            public TaskListDomain mapRow(ResultSet rs, int rowNum)
//                    throws SQLException {
//                // TODO Auto-generated method stub
//                TaskListDomain domain = new TaskListDomain();
//                domain.setId(rs.getString("id"));
//                domain.setCourseName(rs.getString("name"));
//                domain.setTaskName(rs.getString("TASK_NAME"));
////                domain.setApproval(rs.getInt("yi"));
////                domain.setSubmitted(rs.getInt("commit1"));
////                domain.setTotalSubmitted(rs.getInt("total"));
//                return domain;
//            }
//        };
//		Map<String, Object> pageInfor = pageJdbcUtil.getPageInfor(domain.getPageSize(), domain.getPageNumber(), taskRm, sort, querySql, countSql);
////		List<TaskListDomain> info = pageJdbcUtil.getInfo(sql, taskRm);
//		List<TaskListDomain> o = (List<TaskListDomain>) pageInfor.get(ApiReturnConstants.DATA);
//		List<TaskListDomain> o1=new ArrayList<>();
//		for (TaskListDomain t: o) {
//			Integer pending = taskStuInforRepository.countByReleaseTaskIdAndTaskStatusAndDeleteFlag(t.getId(), "pending",DataValidity.VALID.getState());
//			Integer approved = taskStuInforRepository.countByReleaseTaskIdAndTaskStatusAndDeleteFlag(t.getId(), "approved",DataValidity.VALID.getState());
//			Integer integer = taskStuInforRepository.countByReleaseTaskIdAndDeleteFlag(t.getId(),DataValidity.VALID.getState());
//			t.setSubmitted(pending);
//			t.setTotalSubmitted(integer);
//			t.setApproval(approved);
//			o1.add(t);
//		}
//		pageInfor.put(ApiReturnConstants.DATA,o1);
//		return pageInfor;
//    }

    //获取任务模板列表
    public List<TaskTemplateDomain> findTaskTemplateList(QueryTaskTemplateDomain domain ,AccountDTO dto){
        String querySql="SELECT t.id task_id , c3.`name` course_name, c1.`name` course_chapter_name,c2.`name` course_minutia_name ,t.TASK_NAME,t1.`name` created_name ,t.CREATED_DATE,t.QUESTIONS_NUM,t.CREATED_BY FROM t_task t LEFT JOIN c_course_chapter c1 ON t.COURSE_CHAPTER_ID=c1.id  LEFT JOIN c_course_chapter c2 ON t.COURSE_MINUTIA_ID=c2.id LEFT JOIN c_course c3 ON t.COURSE_ID=c3.id LEFT JOIN t_user t1 ON t1.id=t.CREATED_BY where t.DELETE_FLAG=0 and t.TEMPLATE_ID="+domain.getTemplateId()+" ORDER BY t.CREATED_DATE DESC";
//        String countSql="SELECT count(*) FROM t_task t LEFT JOIN c_course_chapter c1 ON t.COURSE_CHAPTER_ID=c1.id  LEFT JOIN c_course_chapter c2 ON t.COURSE_MINUTIA_ID=c2.id LEFT JOIN c_course c3 ON t.COURSE_ID=c3.id LEFT JOIN t_user t1 ON t1.id=t.CREATED_BY where t.DELETE_FLAG=0";

//        if (domain.getCourseId()!=null&&!"".equals(domain.getCourseId())){
//            querySql+=" and t.COURSE_ID = '"+domain.getCourseId()+"'";

//            countSql+=" and t.COURSE_ID = '"+domain.getCourseId()+"'";
//        }
//        if (domain.getCourseChapterId()!=null&&0L<domain.getCourseChapterId()){
//            querySql+=" and t.COURSE_CHAPTER_ID = "+domain.getCourseChapterId();
//            countSql+=" and t.COURSE_CHAPTER_ID = "+domain.getCourseChapterId();
//        }
//        if (domain.getCourseMinutiaId()!=null&&0L<domain.getCourseMinutiaId()){
//            querySql+=" and t.COURSE_MINUTIA_ID = "+domain.getCourseMinutiaId();
//            countSql+=" and t.COURSE_MINUTIA_ID = "+domain.getCourseMinutiaId();
//        }
//        List<SortDTO> sort = new ArrayList<SortDTO>();
//        SortDTO sortDto = new SortDTO();
//        sortDto.setKey("t.CREATED_DATE");
//        sortDto.setAsc(true);
//        sort.add(sortDto);
        RowMapper<TaskTemplateDomain> taskTemplate = new RowMapper<TaskTemplateDomain>() {

            @Override
            public TaskTemplateDomain mapRow(ResultSet rs, int rowNum)
                    throws SQLException {
                // TODO Auto-generated method stub
                TaskTemplateDomain domain = new TaskTemplateDomain();
                domain.setId(rs.getString("task_id"));
                domain.setCourseName(rs.getString("course_name"));
                domain.setCourseChapterName(rs.getString("course_chapter_name"));
                domain.setCourseMinutiaName(rs.getString("course_minutia_name"));
                domain.setTaskName(rs.getString("TASK_NAME"));
                domain.setCreatedName(rs.getString("created_name"));
                domain.setCreateDate(rs.getDate("CREATED_DATE"));
                domain.setQuestionNum(rs.getInt("QUESTIONS_NUM"));
                Long l=rs.getLong("CREATED_BY");
                if (l.equals(dto.getId())){
                    domain.setIsEdit(true);
                }else {
                    domain.setIsEdit(false);
                }
                return domain;
            }
        };
//        Map<String, Object> pageInfor = pageJdbcUtil.getPageInfor(domain.getPageSize(), domain.getPageNumber(), taskTemplate, sort, querySql, countSql);
        return pageJdbcUtil.getInfo(querySql, taskTemplate);
    }
     public Integer save(TaskStuInfor infor){
         TaskStuInfor save = taskStuInforRepository.save(infor);
         return 1;
     }
     public void updateQuestionNum(String taskId){
         Task task = taskRepository.findByIdAndDeleteFlag(taskId, DataValidity.VALID.getState());
         Integer integer = taskQuestionsService.countTaskQuestionNum(taskId, DataValidity.VALID.getState());
         task.setQuestionsNum(integer);
         taskRepository.save(task);
     }

}
